#!/usr/bin/env bash

# Run Kerkerkruip's test suite

# The test suite doesn't always work well if old test files exist
rm -f test*

# Set the random seed to the command line argument, if given
# otherwise set it to the time
SEED=${1:-$(date "+%s")}
echo "Setting random seed to $SEED"
./seeder $SEED

# Run the tests non-interactively
echo -e '\nRunning the Kerkerkruip test suite:'
touch noninteractivetests noninteractivetests.glkdata # not sure which one we'll need
COLS=$(tput cols)
../i7/dumb-git -w $COLS Kerkerkruip.gblorb > testlog && rm noninteractivetests* &

# Output test progress
TESTTRANSCRIPT=testtranscript
while [ -f noninteractivetests ]
do
  [ -f $TESTTRANSCRIPT ] || TESTTRANSCRIPT=testtranscript.glkdata
  sleep 1
  PROGRESS=$(grep 'Current progress:' $TESTTRANSCRIPT | tail -n1)
  if [ $CI -a $CI = true ]
  then
    # in Travis - show progress line by line as it develops
    if [ "$LAST_PROGRESS" != "$PROGRESS" ]
    then
      LAST_PROGRESS="$PROGRESS"
      echo "$PROGRESS"
    fi
  else
    # in a terminal... show a status line that rewrites itself
    sleep 1
    tput rmam # disable line wrap
    printf "\r%-${COLS}s" "$PROGRESS" # print line, padded to the right with blank space, for the number of columns on the screen
    tput smam # enable line wrap
  fi
done

# Output the full results
echo -e '\n\n'
sed -n '/Test results/,$p' $TESTTRANSCRIPT | grep -Ev "all passed" > test-results

SUSPICIOUS_PATTERN="\\*\\*\\* Run-Time Problem\b|\\*\\*\\* Error on file |You can't reach into "
if egrep -q "$SUSPICIOUS_PATTERN" $TESTTRANSCRIPT
then
  echo >> test-results
  echo "Possible runtime issues found in test transcript:" >> test-results
  echo >> test-results
  grep -n $SUSPICIOUS_PATTERN $TESTTRANSCRIPT
fi

cat test-results

# Exit
RESULT=$(perl -ne 'if (/Full results: [0-9]+ tests in [0-9]+\/[0-9]+ sets, ([0-9]+) failure(s)?/) { print $1 }' test-results)
exit $RESULT
